package cn.apestar.common.utils.tran;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

import com.alibaba.fastjson.JSONObject;

import cn.apestar.common.dao.CommonDao;
import cn.apestar.common.utils.BeanUtil;
import cn.apestar.common.utils.CacheUtils;
import cn.apestar.common.utils.ObjectUtils;
import cn.apestar.common.utils.SpringContextHolder;
import cn.apestar.common.utils.StringUtils;
import cn.apestar.common.utils.excel.ImportExcel;

public class TranslateUtil {

    public static TranslateUtil t = new TranslateUtil();

    public static String T_DX = "1";

    public static String T_MAP = "2";

    public static String T_JSON = "3";

    /***
     * 获取缓存公共资源
     * @param list
     * @param c
     * @return
     */
    public List getCacheListByTransLateCondition(TransLateCondition c, Boolean cacheEnable) {

        CommonDao commonService = (CommonDao) SpringContextHolder.getBean("commonDao");
        String colName = c.getColName();
        String key = c.getKey();
        String table = c.getTable();
        String tableKey = c.getTableKey();
        String cols[] = colName.split(",");
        String otherParam[] = c.getOtherParam();
        StringBuffer sql = new StringBuffer("select ").append(colName).append("," + tableKey).append(" from " + table + " where 1=1 ");
        if (otherParam != null) {
            for (String s : otherParam) {
                if (!StringUtils.isEmpty(s)) {
                    sql.append(" and " + s);
                }
            }
        }
        List<Map<String, Object>> dataList = new ArrayList();
        if (cacheEnable) {
            dataList = (List<Map<String, Object>>) CacheUtils.get(CacheUtils.SYS_MENU, sql.toString());
            if (dataList == null || dataList.size() < 0) {
                dataList = commonService.findListBySQL(sql.toString());
                CacheUtils.put(CacheUtils.SYS_MENU, sql.toString(), dataList);
            }
        } else {
            dataList = commonService.findListBySQL(sql.toString());
        }
        return dataList;
    }

    /**
     * 翻译枚举类型
     * @author lvh 2016年2月6日 上午8:36:41</br>
     * @param list
     * @param skey
     * @param tkey
     * @param e
     * @return void
     */
    public static void translatEnumList(List list, String skey, String tkey, List<HashMap> liste) {

        for (int i = 0; i < list.size(); i++) {
            Object o = list.get(i);
            try {
                String value = BeanUtils.getProperty(o, skey);
                if (!StringUtils.isEmpty(value)) {
                    for (int m = 0; m < liste.size(); m++) {
                        HashMap s = liste.get(m);
                        String typeValue = s.get("type_id").toString();
                        if (typeValue.equals(value)) {
                            BeanUtils.setProperty(o, tkey, s.get("type_name").toString());
                        }
                    }
                }
            } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) {
                continue;
            }

        }
    }

    /***
     * 获取缓存公共资源
     * @param list
     * @param c
     * @return
     */
    public static String getCacheListByExcel(String table, String id, String name, String value) {

        CommonDao commonService = (CommonDao) SpringContextHolder.getBean("commonDao");
        StringBuffer sql = new StringBuffer("select ").append(name).append(" as name ,").append(id).append(" as id from " + table + " where 1=1 ");
        List<Map<String, Object>> dataList = (List<Map<String, Object>>) CacheUtils.get(ImportExcel.key, sql.toString());
        if (dataList == null || dataList.size() < 0) {
            dataList = commonService.findListBySQL(sql.toString());
            CacheUtils.put(ImportExcel.key, sql.toString(), dataList);
        }

        for (Map data : dataList) {
            String cd1 = ObjectUtils.toString(data.get("name"), "");
            if (!StringUtils.isEmpty(value)) {
                if (value.equals(cd1)) {
                    return ObjectUtils.toString(data.get("id"), "");
                }
            }
        }
        return value;
    }

    /**
     * 翻译对象
     * @param o
     * @param c
     * @param dataList
     * @param type 1 对象 2 map
     * @return
     */
    public Object translateCommon(Object m, TransLateCondition c, List<Map<String, Object>> dataList, String type) {

        String key = c.getKey();
        String table = c.getTable();
        String colName = c.getColName();
        String tableKey = c.getTableKey();
        String cols[] = colName.split(",");
        StringBuffer buffer = new StringBuffer();
        // 对象
        if (T_DX.equals(type)) {
            String cd = ObjectUtils.toString(BeanUtil.getProperty(m, key), null);
            if (StringUtils.isEmpty(cd)) {
                return m;
            }
            for (Map data : dataList) {

                String cd1 = ObjectUtils.toString(data.get(tableKey), "");
                if (cd.contains(",")) {
                    String[] cd1s = cd.split(",");
                    for (int u = 0; u < cd1s.length; u++) {
                        String cd2 = ObjectUtils.toString(cd1s[u], null);
                        if (cd2 != null && cd2.equals(cd1)) {
                            String field = toJavaAttributeName(colName);
                            String ml = (String) data.get(field);
                            if (!StringUtils.isEmpty(ml)) {
                                buffer.append(ml);
                                buffer.append(",");
                            }
                        }
                    }
                    // BeanUtil.setProperty(m, colName, buffer.toString());
                    for (String field : cols) {
                        field = toJavaAttributeName(field);
                        BeanUtil.setProperty(m, field, buffer.toString());
                    }
                } else if (cd.equals(cd1)) {
                    for (String field : cols) {
                        field = toJavaAttributeName(field);
                        BeanUtil.setProperty(m, field, toStringS(data.get(field)));
                    }
                    break;
                }

            }
        }
        // map
        else if (T_MAP.equals(type)) {
            if (!(m instanceof HashMap)) {
                return m;
            }
            HashMap L = (HashMap) m;
            String cd = ObjectUtils.toString(L.get(key), null);
            if (StringUtils.isEmpty(cd)) {
                return m;
            }
            for (Map data : dataList) {
                String cd1 = ObjectUtils.toString(data.get(tableKey), "");
                if (cd.contains(",")) {
                    String[] cd1s = cd.split(",");
                    for (int u = 0; u < cd1s.length; u++) {
                        String cd2 = ObjectUtils.toString(cd1s[u], null);
                        if (cd2 != null && cd2.equals(cd1)) {
                            String field = toJavaAttributeName(colName);
                            String ml = (String) data.get(field);
                            if (!StringUtils.isEmpty(ml)) {
                                buffer.append(ml);
                                buffer.append(",");
                            }
                        }
                    }
                    L.put(toJavaAttributeName(colName), buffer.toString());
                } else if (cd.equals(cd1)) {
                    for (String field : cols) {
                        field = toJavaAttributeName(field);
                        L.put(field, toStringS(data.get(field)));
                        if (!StringUtils.isEmpty(field) && field.contains("serviceVillage")) {
                            L.put("communtityX", toStringS(data.get("x")));
                            L.put("communtityY", toStringS(data.get("y")));
                        }
                    }
                    break;
                }
            }
        } else if (T_JSON.equals(type)) {
            if (!(m instanceof JSONObject)) {
                return m;
            }
            JSONObject L = (JSONObject) m;
            String cd = L.getString(key);
            if (StringUtils.isEmpty(cd)) {
                return m;
            }
            for (Map data : dataList) {
                String cd1 = ObjectUtils.toString(data.get(tableKey), "");
                if (cd.contains(",")) {
                    String[] cd1s = cd.split(",");
                    for (int u = 0; u < cd1s.length; u++) {
                        String cd2 = ObjectUtils.toString(cd1s[u], null);
                        if (cd2 != null && cd2.equals(cd1)) {
                            String field = toJavaAttributeName(colName);
                            String ml = (String) data.get(field);
                            if (!StringUtils.isEmpty(ml)) {
                                buffer.append(ml);
                                buffer.append(",");
                            }
                        }
                    }
                    L.put(toJavaAttributeName(colName), buffer.toString());
                } else if (cd.equals(cd1)) {
                    for (String field : cols) {
                        field = toJavaAttributeName(field);
                        L.put(field, toStringS(data.get(field)));
                    }
                    break;
                }
            }
        }
        return m;
    }

    /**
     * 转化为JAVA数据
     * @param dbColumnName
     * @return
     */
    public static String toJavaAttributeName(String dbColumnName) {

        if (dbColumnName.indexOf(" as ") > 0) {
            dbColumnName = dbColumnName.substring(dbColumnName.indexOf(" as ") + 4, dbColumnName.length());
        }
        if (dbColumnName.indexOf(".") > 0) {
            dbColumnName = dbColumnName.substring(dbColumnName.indexOf(".") + 1, dbColumnName.length()).trim();
        }
        return dbColumnName;
    }

    /**
     * 翻译集合
     * @param list
     * @param c
     * @return
     */
    public List translateList(List list, TransLateCondition c, Boolean cache) {

        List<Map<String, Object>> dataList = getCacheListByTransLateCondition(c, cache);
        for (Object m : list) {
            translateCommon(m, c, dataList, T_DX);
        }
        return list;
    }

    /**
     * 翻译单个对象
     * @param list
     * @param c
     * @return
     */
    public Object translateListT(Object o, TransLateCondition c, Boolean cacheEnable) {

        List<Map<String, Object>> dataList = getCacheListByTransLateCondition(c, cacheEnable);
        o = translateCommon(o, c, dataList, T_DX);
        return o;
    }

    /**
     * 翻译JSON OBEJCT
     */
    public Object translateListJsonObject(Object o, TransLateCondition c, Boolean cache) {

        List<Map<String, Object>> dataList = getCacheListByTransLateCondition(c, cache);
        if (!(o instanceof JSONObject)) {
            return o;
        }
        translateCommon(o, c, dataList, T_JSON);
        return o;
    }

    /**
     * 翻译JSON OBEJCT集合
     */
    public List translateListJsonObjectList(List list, TransLateCondition c, Boolean cache) {

        List<Map<String, Object>> dataList = getCacheListByTransLateCondition(c, cache);

        for (Object m : list) {
            translateCommon(m, c, dataList, T_MAP);
        }
        return list;
    }

    /**
     * 翻译房屋
     * @param list
     */
    public List translateJSONObjectList(List list) {

        return list;
    }

    /**
     * 格式化返回值
     */
    public static String toStringS(Object o) {

        if (o == null) {
            return "";
        } else {
            return o.toString().replaceAll(" ", "");
        }

    }
}
